<?
    require_once("mvc/action/Action.php");
    require_once("cms/newsletter/om/NewsletterPeer.php");
    require_once("cms/newsletter/om/NewsletterLanguagePeer.php");

    class SaveAction extends Action {

        private $log;

        public function __construct() {
            $this->log =& LoggerManager::getLogger("SaveAction");
        }

        public function execute(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

            $errors = new ActionMessages();

            $newsletter =& $form->getNewsletter();
            $newsletter->setModifiedDate(date(_Core::FORMAT_SQLDATETIME));
            
            $conn = Propel::getConnection();

            try {

                $conn->begin();

                if($newsletter->getNewsletterId() > 0) {

                    $c = new Criteria();
                    $c->add(NewsletterLanguagePeer::NEWSLETTER_ID,
                        $newsletter->getNewsletterId());
                    NewsletterLanguagePeer::doDelete($c, $conn);

                    NewsletterPeer::doUpdate($newsletter, $conn);

                } else {

                    $newsletter->setStatus("draft");
                    $newsletter->setInsertDate(date(_Core::FORMAT_SQLDATETIME));
                    $newsletter->setNewsletterId(
                        NewsletterPeer::doInsert($newsletter, $conn)
                    );

                }

                // Insert the newsletter languages.
                foreach($form->getLanguages() as $code) {
                    $newsletterLanguage = new NewsletterLanguage();
                    $newsletterLanguage->setNewsletterId($newsletter->getNewsletterId());
                    $newsletterLanguage->setLanguageCode($code);
                    NewsletterLanguagePeer::doInsert($newsletterLanguage, $conn);
                }

                $conn->commit();

            } catch(PropelException $e) {
                $conn->rollback();
                $errors->add(ActionMessage::GLOBAL_MESSAGE,
                    new ActionMessage("error.save"));
                $this->log->error($e->getMessage());
            }


            // Send a test email.
            if(strlen($form->getEmail()) > 0) {

                require_once "swift/Swift.php";
                require_once "swift/Swift/Connection/NativeMail.php";

                try {

                    // Start Swift
                    $swift = new Swift(new Swift_Connection_NativeMail());

                    // Create the message
                    $message = new Swift_Message($form->getNewsletter()->getSubject());

                    $base = $request->getContext()->getInitParameter(_Newsletter::BASE);

                    ob_start();
                    include($request->getContext()->getInitParameter(_Newsletter::HEADER));
                    $header = ob_get_contents();
                    ob_end_clean();

                    ob_start();
                    include($request->getContext()->getInitParameter(_Newsletter::FOOTER));
                    $footer = ob_get_contents();
                    ob_end_clean();

                    // get some i18n resources
                    $resources = $request->getContext()->getAttribute("php-cms-newsletternewsletter");
                    $locale = new Locale($request->getContext()->getInitParameter(_Core::DEFAULT_LANGUAGE));
                    $text = $resources->getMessage($locale, "mail.text");

                    // Add some plain text
                    // Todo: Provide online newsletter link.
                    $message->attach(
                        new Swift_Message_Part(
                            $text, "text/plain", null, "utf-8"));

                    // Add html
                    $body = str_replace(
                                array("{base}", "{name}"),
                                array($base, "Tester"),
                                ($header.$form->getNewsletter()->getBody().$footer)
                            );

                    $message->attach(new Swift_Message_Part($body, "text/html", null, "utf-8"));

                    //Now check if Swift actually sends it
                    $swift->send($message, $form->getEmail(), EMAIL_FROM);


                } catch (Swift_Connection_Exception $e) {
                    $errors->add(ActionMessage::GLOBAL_MESSAGE,
                        new ActionMessage("There was a problem communicating with MAIL."));
                    $this->log->errors($e);
                } catch (Swift_Message_MimeException $e) {
                    $errors->add(ActionMessage::GLOBAL_MESSAGE,
                        new ActionMessage("There was an unexpected problem building the email."));
                    $this->log->errors($e);
                }

            }


            // Return any save errors.
            if(!$errors->isEmpty()) {
                $this->saveErrors($request, $errors);
                return $mapping->getInputForward();
            }


            // Reset the newsletterListForm from & to session.
            $session  = $request->getSession();
            $listForm = $session->getAttribute("cms/newsletterListForm");
            $listForm->setPage(0);
            $session->setAttribute("cms/newsletterListForm", $listForm);


            // To the success newsletter.
            return $mapping->findForward("success");

        }

    }
?>